
import 'package:boss/main.dart';
import 'package:boss/models/commodity.dart';
import 'package:boss/models/offers.dart';
import 'package:boss/models/sku.dart';
import 'package:boss/ui/page/offersManagement/constant/offers_constant.dart';
import 'package:boss/ui/page/offersManagement/page/plusOffersMode/page/provider/base_provider.dart';
import 'package:boss/ui/widget/loading/loading.dart';
import 'package:hi_common/hi_common.dart';

class OrderDiscountProvider extends BaseProvider {
  String discountRate = '';

  OrderDiscountProvider({Offers data}) {
    super.initData(data: data);

    if (data != null) {
      discountRate = data.orderDiscountList[0].discountRate.toString();

      if (data.orderDiscountCount > 0) {
        data.orderDiscountList.forEach((item) {
          var commodity = Commodity.fromJson({
            'title': item.comPropertiesDTO.title,
            'id': item.commodityId,
            'price': item.comPropertiesDTO.price,
            'unit': item.comPropertiesDTO.unit,
          });

          if (item.skuId != 0) {
            commodity.commoditySkuList = [
              Sku.fromJson({
                'skuId': item.skuId,
                'skuName': item.comPropertiesDTO.commoditySkuName,
                'skuPrice': item.comPropertiesDTO.price,
              })
            ];
          }

          commoditys.add(commodity);
        });
      }
    }
  }

  setDiscountRate(String value) {
    discountRate = value;
    notifyListeners();
  }

  Future<bool> addOrderDiscountOffer() async {
    try {
      if (offerName == null || offerName == '') {
        toast('请填写优惠名称');
        return false;
      }
      if (discountRate == null || discountRate == '') {
        toast('请填写折扣率');
        return false;
      }

      showLoadingToast();

      Map<String, dynamic> data = {
        'commodityCustomList': commoditys == null
            ? null
            : commoditys
                .map((item) => {
                      'commodityId': item.id,
                      'skuId': item.sku?.skuId,
                    })
                .toList(),
        'discountRate': discountRate,
        'storeDiscountStandard': {
          'activityName': offerName,
          'activityType': activityType,
          'discountType': OffersConstant.order_discount,
          'type': OffersConstant.order_offers,
          'supportQrcode': 0,
        },
      };

      setDateTimeForHttpData(data);

      var result = await api.addOrderDiscount(data);

      if (!result.successful()) {
        toast(result.msg);
        return false;
      }
      toast('添加成功');
      return true;
    } catch (e) {
      toast(e.toString());
      return false;
    } finally {
      hideLoadingToast();
    }
  }
}
